package com.ultrasoft.farmasoft.web;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ultrasoft.farmasoft.domain.Activesubstance;
import com.ultrasoft.farmasoft.domain.Composition;
import com.ultrasoft.farmasoft.domain.Item;
import com.ultrasoft.farmasoft.domain.Package;
import com.ultrasoft.farmasoft.domain.Pharmacyproduct;
import com.ultrasoft.farmasoft.domain.Product;
import com.ultrasoft.farmasoft.domain.Productattributes;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Stock;
import com.ultrasoft.farmasoft.domain.Typecomposition;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.service.ConfigServiceProducts;
import com.ultrasoft.farmasoft.service.ProviderService;
import com.ultrasoft.farmasoft.service.ReportsService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;

@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Reports")
public class ReportsLogisticsReportsController {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	private String providerId_ 		= "_providerId";

	private final ReportsService reportsService;
	private final ConfigServiceProducts configServiceProducts;
	private final ProviderService providerService;
	@Autowired
	public ReportsLogisticsReportsController(ProviderService providerService,ConfigServiceProducts configServiceProducts,ReportsService reportsService){
		this.reportsService 		= reportsService;
		this.configServiceProducts	= configServiceProducts;
		this.providerService 		= providerService;
	}
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String handleLogisticsReports(HttpServletRequest request,String headMain) {
    	try {
    		return "redirect:/"+headMain+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+
    				"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_)+
    				"&"+UtilCommon.optionId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.optionId_); 
		} catch (Exception e) {
			return redirectLogisticsReports(request);
		}
    }
	private String redirectLogisticsReports(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/Reports/logisticsReports?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	@RequestMapping(value="/logisticsReports", method=RequestMethod.GET)
	public String handleRequestLogisticsReports(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			return UtilCommon.fReports_LogisticsReports+"logisticsReports";
		}else
			return redirectLogisticsReports(request);
	}
	@RequestMapping(value="/ProductReportsMissing/productReportsMissing", method=RequestMethod.GET)
	public String handleRequestLogisticsReportsProductReportsMissing(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){			
			model.addAttribute("listObject",reportsService.getListObjectProductByStatePackageByStateItem());	
			model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
			return UtilCommon.fReports_LogisticsReports_ProductReportsMissing+"productReportsMissing";
		}else
			return redirectLogisticsReports(request);
	}	
	@RequestMapping(value="/ProductReportsProviders/productReportsProviders", method=RequestMethod.GET)
	public String handleRequestLogisticsReportsProductReportsByProviders(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){			
			int tempProviderId=UtilConverter.converterStringToInteger(request,providerId_);
    		if(tempProviderId > -1){
    			if(tempProviderId == 0){
    				model.addAttribute("listProduct",configServiceProducts.getListProductByPharmacyId(s_pharmacyId,true));    			
    			}else
    				model.addAttribute("listProduct",configServiceProducts.getListProductByPharmacyIdByProviderId(s_pharmacyId, tempProviderId, true));
    			model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
    			return UtilCommon.fReports_LogisticsReports_ProductReportsProviders+"productReportsProviders";
    		}else
    			if(tempProviderId == -1)
    				return handleLogisticsReports(request,"Reports/ProductReportsProviders/productReportsProviders?")+"&"+providerId_+"=0";    		
    			else{
    				model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
        			return UtilCommon.fReports_LogisticsReports_ProductReportsProviders+"productReportsProviders";
    			}
		}else
			return redirectLogisticsReports(request);
	}
	@RequestMapping(value="/ProductReportsExpiredProducts/productReportsExpiredProducts", method=RequestMethod.GET)
	public String handleRequestLogisticsReportsProductReportsExpiredProducts(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){			
			int tempProviderId=UtilConverter.converterStringToInteger(request,providerId_);
    		if(tempProviderId > -1){
    			if(tempProviderId == 0){
        			model.addAttribute("listProduct",getListProductTemp(configServiceProducts.getListProductByPharmacyIdCompleteByState(s_pharmacyId,true,(short)1))); 			
    			}else
    				model.addAttribute("listProduct",configServiceProducts.getListProductByPharmacyIdByProviderCompleteByState(s_pharmacyId, tempProviderId, true,(short)1));
    			Calendar calendarNow = Calendar.getInstance();
    			model.addAttribute("daysForExpired",14);
    			model.addAttribute("dateNow",calendarNow.getTime());
    			model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
    			return UtilCommon.fReports_LogisticsReports_ProductReportsExpiredProducts+"productReportsExpiredProducts";
    		}else
    			if(tempProviderId == -1)
    				return handleLogisticsReports(request,"Reports/ProductReportsExpiredProducts/productReportsExpiredProducts?")+"&"+providerId_+"=0";    		
    			else{
    				model.addAttribute("listProvider",providerService.getListProvider(s_pharmacyId,true));
        			return UtilCommon.fReports_LogisticsReports_ProductReportsExpiredProducts+"productReportsExpiredProducts";
    			}
		}else
			return redirectLogisticsReports(request);
	}
		
	
	private ArrayList<Product> getListProductTemp(List<Product> listProductTemp){
		ArrayList<Product> listProduct = new ArrayList<Product>();
		for (Product product : listProductTemp) {			
			listProduct.add(getProductTemp(product));
		}
		return listProduct;
	}
	private Product getProductTemp(Product product){
		Product p = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
		p.setName(product.getName());
		p.setPresentation(product.getPresentation());
		p.setActive(product.getActive());
		p.setGenericName(product.getGenericName());
		Activesubstance as = new Activesubstance(product.getActiveSubstanceId().getActiveSubstanceId(),product.getActiveSubstanceId().getSynonyms(),product.getActiveSubstanceId().getName(),product.getActiveSubstanceId().getTherapeuticAction(),product.getActiveSubstanceId().getProperties());
		p.setActiveSubstanceId(as);
		p.setCode(product.getCode());
		p.setCodeBar(product.getCodeBar());
		
		Provider provider = new Provider(product.getProvider().getProviderId(),product.getProvider().getName(),product.getProvider().getClient());
		if(product.getProvider().getAddress() != null)
			provider.setAddress(product.getProvider().getAddress());
		p.setProvider(provider);			
		
		List<Composition> listCompositionTemp = (List<Composition>)product.getCompositionCollection();
		List<Composition> listComposition = new ArrayList<Composition>();
		for (Composition c : listCompositionTemp) {
			Composition composition = new Composition(c.getCompositionId(),c.getName(),c.getQuantity(),c.getActive());
			Typecomposition typeComposition = new Typecomposition(c.getTypeCompositionId().getTypeCompositionId(),c.getTypeCompositionId().getName());
			composition.setTypeCompositionId(typeComposition);
			Product p1 = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
			p1.setName(product.getName());
			p1.setPresentation(product.getPresentation());
			p1.setActive(product.getActive());
			p1.setGenericName(product.getGenericName());
			composition.setProduct(p1);
			listComposition.add(composition);
		}
		List<Productattributes> listProductAttributesTemp = (List<Productattributes>)product.getProductattributesCollection();
		List<Productattributes> listProductAttributes = new ArrayList<Productattributes>();
		for (Productattributes pa : listProductAttributesTemp) {
			Productattributes productAttributes = new Productattributes(pa.getProductattributesPK().getProductAttributeId(),pa.getProductattributesPK().getProviderId(),pa.getProductattributesPK().getProductId()); 
			listProductAttributes.add(productAttributes);
		}
		p.setCompositionCollection(listComposition);
		p.setProductattributesCollection(listProductAttributes);
		
		if(product.getPharmacyProduct() != null){
			Pharmacyproduct pp = new Pharmacyproduct(product.getPharmacyProduct().getPharmacyproductPK().getPharmacyId(),product.getPharmacyProduct().getPharmacyproductPK().getProviderId(),product.getPharmacyProduct().getPharmacyproductPK().getProductId()); 
			pp.setRepositionLevel(product.getPharmacyProduct().getRepositionLevel());
			pp.setPackage1(product.getPharmacyProduct().getPackage1());
			pp.setService(product.getPharmacyProduct().getService());
			pp.setRequiresPrescription(product.getPharmacyProduct().getRequiresPrescription());
			pp.setLocation(product.getPharmacyProduct().getLocation());
			pp.setActive(product.getPharmacyProduct().getActive());
			List<Package> listPackage = new ArrayList<Package>(); 
			List<Package> listPackageTemp = (List<Package>)product.getPharmacyProduct().getPackageCollection();	
			for (Package package1 : listPackageTemp) {
				List<Item> listItem = new ArrayList<Item>();
				List<Item> listItemTemp = (List<Item>)package1.getItemCollection();
				for (Item item : listItemTemp) {
					Item itemTemp = new Item(item.getItemPK().getPackageId(),item.getItemPK().getItemId());
					Stock s = new Stock(item.getStockId().getStockId(),item.getStockId().getName());
					itemTemp.setState(item.getState());
					itemTemp.setCost(item.getCost());
					itemTemp.setStockId(s);
					listItem.add(itemTemp);
				}
				Package pack = new Package(package1.getPackageId(),package1.getPackage1(),package1.getDateIncome(),package1.getDueDate());
				pack.setBatchNumber(package1.getBatchNumber());
				pack.setDueDate(package1.getDueDate());
				pack.setState(package1.getState());
				if(package1.getTempTotal1() != null)
					pack.setTempTotal1(package1.getTempTotal1());
				
				if(package1.getTempTotal2() != null)
					pack.setTempTotal2(package1.getTempTotal2());
				
				pack.setItemCollection(listItem);
				listPackage.add(pack);
			}	
			pp.setPackageCollection(listPackage);
			p.setPharmacyProduct(pp);
		}
		return p;
	}
}
